import re, json
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest
from django.middleware.csrf import get_token ,rotate_token
from django.views.generic import View
from django.contrib.auth import authenticate, login

from apps.comm import define_info
from apps.user.models import UserInfo
# Create your views here.
from apps.comm import token


_info = define_info.res_info


# /user/register
class RegisterView(View):
    # 注册
    def get(self, request):
        _info['msg'] = 'successful'
        _info['result'] = {'token': get_token(request)}

        print('get token!!')
        return HttpResponse(json.dumps(_info, ensure_ascii=False), content_type="application/json,charset=utf-8")

    def post(self, request):
        """注册处理"""
        # 接收数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')

        print(username)
        print(password)
        print(email)

        # 进行数据校验
        if not all([username, password, email]):
            # 数据不完整
            _info['msg'] = '信息不完整'
            return HttpResponse(json.dumps(_info))

        # 校验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            _info['msg'] = '邮箱格式不正确'
            return HttpResponse(json.dumps(_info))

        # 校验用户名是否重复
        try:
            user = UserInfo.objects.get(username=username)
        except Exception as ex:
            # 用户名不存在
            user = None

        if user:
            # 用户名已存在 ------
            _info['msg'] = '用户已经存在'
            return HttpResponse(json.dumps(_info))

        # 进行用户注册
        # user = UserInfo.objects.create_user(username, email, password)
        # user.is_active = 1  # 激活
        # user.save()

        # 返回应答
        _info['msg'] = 'successful'
        _info['result'] = 'ok'
        return HttpResponse(json.dumps(_info))


class LoginView(View):
    def get(self, request):
        return token.token(request)

    def post(self, request):
        """登录校验"""
        # 接收数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 校验数据
        if not all([username, password]):
            # 数据不完整
            _info['msg'] = '信息不完整'
            return HttpResponse(json.dumps(_info))
        # 登录校验
        user = authenticate(username=username, password=password)
        if user is not None:  # 用户名密码正确
            # 记录用户的登录状态
            # login(request, user)
            request.session['username'] = user.username
            request.session['is_login'] = True

            _info['msg'] = '登录成功'
            _info['result'] = '登录成功'
            res = HttpResponse()
            res.content = json.dumps(_info)
            res.set_cookie('username', username, max_age=120)
            return res

        else:
            # 用户名或密码错误
            _info['msg'] = '用户名或密码错误'
            _info['result'] = '登录错误'
            return HttpResponse(json.dumps(_info))

